<?php
namespace app\common\model;
use x\Xbase;
class GoodsCart extends Xbase
{

    /**添加购物车
     * @param $d
     * @param $cart_count
     */
    public function add($goods_price_id,$cart_count,$user_id){
        $goods_price = $this->db->find("goods_price",$goods_price_id);
        if(!$goods_price){
            $this->setError("参数错误");
            return 0;
        }
        if($goods_price['stock'] < $cart_count){
            $this->setError("库存不足");
            return 0;
        }
        $rs = $this->db->query('select * from order_cart where user_id = ? and goods_id = ? and goods_price_id = ?',[$user_id,$goods_price['goods_id'],$goods_price['id']],1);
        if($rs){
            $cart_count += $rs['nums'];
            $rs = $this->db->update('order_cart',['nums'=>$cart_count],['user_id = ? and goods_id = ? and goods_price_id = ?',[$user_id,$goods_price['goods_id'],$goods_price['id']]]);
        }else{
            $data = [
                'user_id'=>$user_id,
                'goods_id'=>$goods_price['goods_id'],
                'goods_price_id'=>$goods_price['id'],
                'nums'=>$cart_count,
                'create_time'=>time(),
            ];
            $this->db->insert('order_cart',$data);
        }
        return $cart_count;
    }

    /**
     * 获取购物车
     */
    public function getCart($user_id){
        $cart_list = $this->db->query("select a.*,o.id as cart_id,b.postage,b.title as goods_name,b.pic,o.nums from order_cart as o inner join goods_price a on o.goods_price_id = a.id left join goods b on a.goods_id=b.id where o.user_id = ?",[$user_id]);
        $cart_arr = [];
        foreach ($cart_list as $k => $v) {
            $cart = [$v['id'],$v['goods_id'],$v['nums']];
            $cart_arr[] = $cart;
        }
        $d = [
            'cart_list' => $cart_list,
            'cart_arr' => $cart_arr,
        ];
        return $d;
    }

    /**删除购物车商品
     * @param $user_id
     * @param $id
     * @return mixed
     */
    public function deltCart($user_id,$id){
        $rs = $this->db->query('delete from order_cart where user_id = ? and id = ?',[$user_id,$id]);
        return $rs;
    }
}
